package org.xtb.BS.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.xtb.BS.service.ContactsService;
import org.xtb.pojo.Contacts;
import org.xtb.pojo.Result;

import java.util.List;

@RestController
@RequestMapping(value = "/contacts")
public class ContactsController {
    @Autowired
    private ContactsService service;

    @GetMapping
    @ResponseBody
    public Result<List<Contacts>> getAllContacts() {
        return new Result<>(true,2000,"获取全部数据成功",service.getAll());
    }

    @ResponseBody
    @PostMapping
    public Result<Contacts> addContact(@RequestBody Contacts contact) {
        Result<Contacts> result;
        Boolean aBoolean = service.addOne(contact);
        List<Contacts> list = service.getAll();
        result=(aBoolean ? new Result<>(true,2000,"添加成功",list.get(list.size()-1)): new Result<>(false,2001,"添加失败"));
        return result;
    }

    @ResponseBody
    @PutMapping("/{id}")
    public Result<Contacts> updateContact(@PathVariable int id, @RequestBody Contacts contact) {
        contact.setId(id);
        Result<Contacts> result;
        result=(service.updateOne(contact)? new Result<>(true,2000,"修改成功",contact): new Result<>(false,2001,"修改失败",contact));
        return result;
    }

    @ResponseBody
    @DeleteMapping("/{id}")
    public void deleteContact(@PathVariable int id) {
        Contacts delete = new Contacts();
        delete.setId(id);
        service.deleteOne(delete);
    }
}
